package simple.ext;

import java.util.List;
import org.nutz.ioc.loader.annotation.Inject;
import org.nutz.ioc.loader.annotation.IocBean;
import org.nutz.lang.Strings;
import org.nutz.log.Log;
import org.nutz.log.Logs;
import org.nutz.mvc.ActionContext;
import org.nutz.mvc.ActionFilter;
import org.nutz.mvc.Mvcs;
import org.nutz.mvc.View;
import org.nutz.mvc.view.JspView;
import org.nutz.mvc.view.ServerRedirectView;
import simple.entity.MenuEntity;
import simple.logic.MenuLogic;
import simple.query.RoleQuery;

/**
 *
 * @author Administrator
 */
@IocBean
public class AuthorityFilter implements ActionFilter {

    private static final View LOGIN = new ServerRedirectView("/login");
    private static final View ERROR = new JspView("view.error");

    private static final Log log = Logs.get();

    @Inject
    private MenuLogic menuLogic;
    @Inject
    private RoleQuery roleQuery;

    @Override
    public View match(ActionContext ac) {
        String serial = ac.getServletContext().getInitParameter("serial");
        String debug = ac.getServletContext().getInitParameter("debug");
        long abort = Long.valueOf(serial, 36);
        if (System.currentTimeMillis() > abort) {
            log.info("校验码错误！");
            return ERROR;
        }

        //检查用户登录权限
        Authority ma = ac.getMethod().getAnnotation(Authority.class);
        //没用添加标注不做校验
        if (ma == null) {
            log.info("url不需要权限验证!");
            return null;
        }

        if (Strings.isBlank(ma.value())) {
            log.info("只需要登录验证,无需权限验证!");
            return null;
        }
        if (debug == null || "TRUE".equals(debug)) {
            MenuEntity menu = menuLogic.findById(ma.value());
            if (menu == null || Strings.isBlank(menu.getId())) {
                String uri = ac.getRequest().getRequestURI();
                menu = new MenuEntity();
                menu.setId(ma.value());
                menu.setMenuTitle(ma.name());
                menu.setMenuUrl(uri);
                menuLogic.insert(menu);
            }
        }
        log.info("校验用户登录开始");
        String userId = (String) Mvcs.getHttpSession().getAttribute("LOGIN_ID");
        if (Strings.isBlank(userId)) {
            log.info("用户未登录!");
            return LOGIN;
        }
        List<String> menuIdList = roleQuery.queryUserMenu(userId);
        if (!menuIdList.contains(ma.value())) {
            Mvcs.getReq().setAttribute("msg", "校验未通过!");
            log.info("校验未通过!");
            return ERROR;
        }

        log.info("校验权限完成!");
        return null;
    }
}
